package chen.web.user;

import java.util.Calendar;
import java.util.Date;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import chen.web.DataSourceProvider;
import chen.web.event.EventListener;
import chen.web.user.event.OfflineEvent;
import chen.web.user.event.OnlineEvent;

public class RecordOnlineSecondsListeners{

	private static SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(DataSourceProvider.getDataSource());

	/**
	 * 记录最后一次上线时间
	 * @author chen
	 *
	 */
	public static class MyOnlineListener implements EventListener<OnlineEvent>{
		private static final String SQL_1 = "update web_account set acc_lastOnline = ? where acc_id = ?";
		@Override
		public void listen(OnlineEvent event) {
			// TODO Auto-generated method stub
			Account account = event.getOnlineAccount();
			account.setLastOnline(new Date());
			simpleJdbcTemplate.update(SQL_1, account.getLastOnline(), account.getId());
		}
		
	}
	
	/**
	 * 记录最后一次下线时间，并更新总的在线时间
	 * @author chen
	 *
	 */
	public static class MyOfflineListener implements EventListener<OfflineEvent>{
		private static final String SQL_1 = "update web_account set acc_lastOffline = ? where acc_id = ?";
		private static final String SQL_2 = "update web_account set acc_onlineSeconds = ? where acc_id = ?";
		
		private int sessionTimeout;
		/**
		 * @param sessionTimeout	会话超时时间，单位分钟
		 */
		public MyOfflineListener(int sessionTimeout){
			this.sessionTimeout = sessionTimeout;
		}
		
		@Override
		public void listen(OfflineEvent event) {
			// TODO Auto-generated method stub
			Account account = event.getOfflineAccount();
			//若自动下线，则下线时间是最后一次与服务器会话的时间
			if(event.isAutoOffline()){
				Calendar cal = Calendar.getInstance();
				cal.roll(Calendar.MINUTE, -sessionTimeout);
				account.setLastOffline(cal.getTime());
			} else {
				account.setLastOffline(new Date());	
			}
			simpleJdbcTemplate.update(SQL_1, account.getLastOffline(), account.getId());
		
			int onlineSeconds = (int) ((account.getLastOffline().getTime() - account.getLastOnline().getTime())/1000);				
			account.increaseOnlineSeconds(onlineSeconds);
			simpleJdbcTemplate.update(SQL_2, account.getOnlineSeconds(), account.getId());
		}
		
	}

}
